--
-- Author: ping.wang
-- Date: 2018-07-06 13:45:58
--
-- AuctionModel
--

local AuctionShopClassify = import(".AuctionShopClassify")--公会天赋数据结构
local AuctionNormalProductVo = import(".AuctionNormalProductVo")
local AuctionBidProductVo = import(".AuctionBidProductVo")

local table_insert = table.insert
local table_remove = table.remove

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ModelBase)

function ClassRef:ctor(data)
    self.super.ctor(self, data)
end

function ClassRef:init()
    --1级分类={二级分类,二级分类}
	self._auctionShopClassify = AuctionShopClassify.new(GD:queryAuctionshop())
    self._normalGoods = {} --普通商品
    self._bidingGoods = {} --竞价商品
    self._curBeginPageIdx = 1 --开始页
    self._totalGoodsCount = 0 --服务器计算出的道具总数量，用于更新页面最大值
    self._isLastPage = true
    self._isNotUseTotalGoodsCount = false

    self._mySaleNormalGoods = {} --我出售的普通商品
    self._mySaleBidingGoods = {} --我出售的竞价商品
end


function ClassRef:getAuctionShopClassifyData()
    local tabId = app:getInst("AuctionController"):getCurrentSelectTabIdx()
    return self._auctionShopClassify:getData(tabId)
end

function ClassRef:getMenuIdxByAuctionType(tabId, typeId)
    local classifyData = self._auctionShopClassify:getData(tabId)
    for i, v in ipairs(classifyData) do
        for k, subData in ipairs(v.subDatas) do
            if subData.id == typeId then
                return i, k
            end
        end
    end
    return 1, 1
end

--参数是由低到高
function ClassRef:sortNormalGoodsByPrice(isUpper)
    table.sort(self._normalGoods,function(a,b)
        local price_a = a:getSellPrice()
        local price_b = b:getSellPrice()
        if isUpper then
            return price_a < price_b
        else
            return price_a > price_b
        end
    end)
end

function ClassRef:sortBiddingGoodsByPrice(isUpper)
    table.sort(self._bidingGoods,function(a,b)
        local price_a = a:getBidingPrice()
        local price_b = b:getBidingPrice()
        if isUpper then
            return price_a < price_b
        else
            return price_a > price_b
        end
    end)
end


--获取所有可以贩售的商品
function ClassRef:getAllItemsCanSell()
    local allItems = UD:getItems()
    local tmp = {}
    for k,v in pairs( allItems ) do
        if not v:isBind() and v:getAcType() ~= 0 then
            tmp[#tmp + 1] = v
        end
    end

    -- 共用背包道具的排序规则
    app:sendMsg("NewBagModel", "sortItems", tmp)

    return tmp
end


function ClassRef:getNormalGoods()
    return self._normalGoods
end

function ClassRef:getBidingGoods()
    return self._bidingGoods
end

function ClassRef:getCurBeginPageIdx()
    return self._curBeginPageIdx
end

function ClassRef:getTotalGoodsCount()
    return self._totalGoodsCount
end

--当前是否是最后一页
function ClassRef:isLastPage()
    return self._isLastPage
end

--商品总数是否有用
function ClassRef:isNotUseTotalCount()
    return self._isNotUseTotalGoodsCount
end

function ClassRef:clearMySaleGoodsData()
    self._mySaleNormalGoods = nil --我出售的普通商品
    self._mySaleBidingGoods = nil --我出售的竞价商品
end

function ClassRef:clearAllData()
    self._normalGoods = nil --普通商品
    self._bidingGoods = nil --竞价商品
    self._curBeginPageIdx = 1 --开始页
    self._totalGoodsCount = 0 --服务器计算出的道具总数量，用于更新页面最大值
    self._isLastPage = true
    self._isNotUseTotalGoodsCount = false

    self._mySaleNormalGoods = nil --我出售的普通商品
    self._mySaleBidingGoods = nil --我出售的竞价商品
end

function ClassRef:getMySaleNormalGoods()
    return  self._mySaleNormalGoods or {}
end


function ClassRef:getMySaleBidGoods()
    return self._mySaleBidingGoods or {}
end

--移除出售列表中的道具 UUID是拍卖行道具的唯一ID，isBid代表是否是竞价商品
function ClassRef:removeMySaleProduct(uuid, isBid)
    if isBid then
        if self._mySaleBidingGoods then
            for k,v in ipairs(self._mySaleBidingGoods) do
                if v:getProductUUId() == uuid then
                    table_remove(self._mySaleBidingGoods,k)
                    break
                end
            end
        end
    else
        if self._mySaleNormalGoods then
            for k,v in ipairs(self._mySaleNormalGoods) do
                if v:getProductUUId() == uuid then
                    table_remove(self._mySaleNormalGoods,k)
                    break
                end
            end
        end
    end
end


----在主界面查询我的出售后调用该方法--------------------------
function ClassRef:setProductList(type,normalData,bidData)
    self._curBeginPageIdx = 1
    if type == Enums.AuctionProductType.normal then
        self._totalGoodsCount = #normalData
        self._normalGoods = normalData
    elseif type == Enums.AuctionProductType.bid then
        self._totalGoodsCount = #bidData
        self._bidingGoods = bidData
    end
end
------------------------ receive ------------------------


------------------------ request ------------------------
--查询商品的指导价
function ClassRef:reqQueryGoodsAveragePrice(uuid,itemId)
    app.session:request("pb_auction.C2S_QueryGoodsAveragePrice",{itemId = itemId,uuid=uuid}, function(ret)
        local id = ret.itemId
        local price = ret.price
        local uuid = ret.uuid
        local itemData = UD:getItem(uuid)

        app:sendMsg( "AuctionController", "openBuyOrSellView",{itemData = itemData, suggestPrice = price, isbuy = false})
    end)
end


--商品上架
function ClassRef:reqOnShelves(uuid,price,count,fixedPrice)
    local sendData = {uuid = uuid,sellPrice = price,sellCount = count}
    if fixedPrice then 
        sendData.buyoutPrice = fixedPrice
    end
    app.session:request("pb_auction.C2S_OnShelves",sendData, function(ret)
        --dump( ret, " ---------->>> reqOnShelves ret" )
        if ret.ok then
            --商品出售成功 刷新我的出售界面
            display.pushToast(string.format(L("auction_tips4"),math.floor(GD:getSystemPar( "auctionSaleWaitingTime")/60) ))
            self:reqMySaleList()
        end
    end)
end

--商品下架 下架无论成功还是失败都要刷新一遍界面
function ClassRef:reqOffShelves(uuid)
    app.session:request("pb_auction.C2S_OffShelves",{uuid = uuid}, function(ret)
        --dump( ret, " ---------->>> reqOffShelves ret" )
        app:sendMsg( "AuctionController", "refreshAfterOffShelves")
        if ret.ok then
            display.pushToast(L("mailtitle_90024"))
        end
    end)
end

--查看商品出售列表
--kind 商品类型（1：普通商品，2：竞价商品)
--sub_menu 二级分类（对应auctionshop表中的ID字段
--quality 品质(默认为0，表示不过滤品质)
--bidding_price_asc 售价排序(0表示不排序，1表示价格从低到高排序，2表示从高到低排序。对于普通商品，基于售价排序；对于竞价商品，基于最高竞价排序)
--pages 页数(0：表示请求所有商品信息，单次请求上限100条;如果页数超限，返回最后一页)
--my_use_lv bool类型 过滤出符合我的使用等级的商品
function ClassRef:reqQuerySaleList(kind,subMenuId,qualityFilter,priceFilter,pageNum,isMyUseLv)
    app.session:request("pb_auction.C2S_QuerySaleList",{kind = kind,sub_menu = subMenuId,quality = qualityFilter,bidding_price_asc = priceFilter,pages = pageNum,my_use_lv = isMyUseLv},
        function(ret)
            self._normalGoods = {}
            self._bidingGoods = {}
            for i,v in ipairs(ret.normalGoods or {}) do
                local good = AuctionNormalProductVo.new(v)
                table_insert(self._normalGoods,good)
            end

            for i,v in ipairs(ret.biddingGoods or {}) do
                local good = AuctionBidProductVo.new(v)
                table_insert(self._bidingGoods,good)
            end

            --dump(self._normalGoods)
            --dump(self._bidingGoods)

            self._curBeginPageIdx = ret.pages or 1

            if not ret.totalGoodsCount or ret.totalGoodsCount == 0 then
                self._totalGoodsCount = 999999
            else
                self._totalGoodsCount = ret.totalGoodsCount
            end

            self._isNotUseTotalGoodsCount = true
            self._isLastPage = ret.lastPage
            --print(self._curBeginPageIdx,self._totalGoodsCount,#self._normalGoods,#self._bidingGoods)

            app:sendMsg( "AuctionController", "refreshAuctionProductList")
    end,{block = true})
end

--查看我的商品出售列表
function ClassRef:reqMySaleList()
    app.session:request("pb_auction.C2S_MySaleList",{}, function(ret)
        self._mySaleNormalGoods = {} --我出售的普通商品
        self._mySaleBidingGoods = {} --我出售的竞价商品
        for i,v in ipairs(ret.normalGoods or {}) do
            local good = AuctionNormalProductVo.new(v)
            table_insert(self._mySaleNormalGoods,good)
        end

        for i,v in ipairs(ret.biddingGoods or {}) do
            local good = AuctionBidProductVo.new(v)
            table_insert(self._mySaleBidingGoods,good)
        end

        --dump(self._mySaleNormalGoods)
        --dump(self._mySaleBidingGoods)
        --通知去刷新界面
        app:sendMsg( "AuctionController", "refreshMySale")
    end)
end

--查看我的竞价商品列表 查看我所竞标的商品
function ClassRef:reqMyBidingList()
    app.session:request("pb_auction.C2S_MyBiddingList",{}, function(ret)
        self._bidingGoods = {}

        for i,v in ipairs(ret.biddingGoods or {}) do
            local good = AuctionBidProductVo.new(v)
            table_insert(self._bidingGoods,good)
        end
        self._curBeginPageIdx = 1 --开始页
        self._totalGoodsCount = #self._bidingGoods
        self._isNotUseTotalGoodsCount = false
        --dump(self._bidingGoods)
        --通知去刷新拍卖行主界面的显示LIST
        app:sendMsg( "AuctionController", "refreshAuctionProductList")
    end)
end


-------------购买商品不可叠加的----------------------
function ClassRef:reqBuyNormalGoods(uuid,count)
    app.session:request("pb_auction.C2S_BuyNormalGoodsNotOverlay",{uuid = uuid,count = count}, function(ret)
        if ret.count < count then
            display.pushToast(string.format(L("auction_tips12"),ret.count))
        else
            display.pushToast(L("auction_tips10"))
        end
        app:sendMsg( "AuctionController", "refreshAfterBuyProducts")
    end)
end

---------购买普通商品 但是是要修改过的--------
function ClassRef:reqBuyNormalFixedGoods(list,count)
    app.session:request("pb_auction.C2S_BuyNormalGoods",{list=list}, function(ret)
        if ret.count < count then
            display.pushToast(string.format(L("auction_tips12"),ret.count))
        else
            display.pushToast(L("auction_tips10"))
        end
        app:sendMsg( "AuctionController", "refreshAfterBuyProducts")
    end)
end

---购买竞价商品----------------------
function ClassRef:reqBuyBidGoods(uuid,price)
    app.session:request("pb_auction.C2S_Bidding",{uuid = uuid,biddingPrice = price}, function(ret)
        if ret.result == 1 then
            display.pushToast(L("auction_tips8"))
        elseif ret.result == 2 then
            display.pushToast(L("auction_tips10"))
        end
        app:sendMsg( "AuctionController", "refreshAfterBuyProducts")
    end)
end

-------根据名字搜索商品---------------
function ClassRef:reqSearchItemsByName(kind,sub_menu,itemIds,pageIdx,isMyUseLv,priceFilter)
    app.session:request("pb_auction.C2S_SearchByItemId",{kind = kind,sub_menu = sub_menu,itemIds = itemIds,pages = pageIdx,my_use_lv = isMyUseLv,bidding_price_asc=priceFilter }, function(ret)
        self._normalGoods = {}
        self._bidingGoods = {}
        for i,v in ipairs(ret.normalGoods or {}) do
            local good = AuctionNormalProductVo.new(v)
            table_insert(self._normalGoods,good)
        end

        for i,v in ipairs(ret.biddingGoods or {}) do
            local good = AuctionBidProductVo.new(v)
            table_insert(self._bidingGoods,good)
        end

        --dump(self._normalGoods)
        --dump(self._bidingGoods)

        --self._curBeginPageIdx = ret.pages or 1
        self._curBeginPageIdx = 1
        self._totalGoodsCount = ret.totalGoodsCount
        self._isNotUseTotalGoodsCount = false
        --print("namesearch",self._curBeginPageIdx,self._totalGoodsCount,#self._normalGoods,#self._bidingGoods)

        app:sendMsg( "AuctionController", "refreshAuctionProductList")
    end,{block = true})
end

-----普通商品列表查询------------
function ClassRef:reqQueryNormalGoodsList(itemId,subMenu)
    app.session:request("pb_auction.C2S_QueryNormalGoodsList",{itemId = itemId, sub_menu = subMenu}, function(ret)
        local normalGoods = {}
        for i,v in ipairs(ret.normalGoods or {}) do
            local good = AuctionNormalProductVo.new(v)
            table_insert(normalGoods,good)
        end
        app:sendMsg( "AuctionController", "refreshNormalBuyView",normalGoods)
    end,{block = true})
end

return ClassRef
